import { ElMessage } from 'element-plus'
import { BASE_URL, TIME_OUT } from './config'
import HYRequest from './request'
import { localCache } from '@/utils/cache'
import { LOGIN_TOKEN } from '@/global/constant'

const hyRequest = new HYRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,

  interceptors: {
    requestSuccessFn: (config) => {
      const token = localCache.getCache(LOGIN_TOKEN)
      if (config.headers && token) {
        // !：not null 的断言操作符，
        config.headers!.Authorization = `Bearer ${token}`
        // config.headers!.Authorization = `Bearer ${token}`
      }
      return config
    },
    requestFailureFn: (err) => {
      return err
    },
    responseSuccessFn: (res: any) => {
      if (res?.code !== 0) {
        ElMessage.error(res.data)
        return Promise.reject(new Error(res.data))
      }
      return res
    },
    responseFailureFn: (err) => {
      return err
    }
  }
})

/* export const hyRequest2 = new HYRequest({
  baseURL: 'http://codercba.com:1888/airbnb/api',
  timeout: 8000,

  interceptors: {
    requestSuccessFn: (config) => {
      return config
    },
    requestFailureFn: (err) => {
      return err
    },
    responseSuccessFn: (res) => {
      return res
    },
    responseFailureFn: (err) => {
      return err
    }
  }
}) */

export default hyRequest
